

<template>
  <div class="app-container p-[0]!">


  <div class="app-container__section" >
      <PlusSearch
          v-bind="getSearchBinds()"
          :columns="columns"
          v-model="searchForm"
      >

        <template #plus-field-startDate>
          <el-date-picker start-placeholder="请选择开始日期" end-placeholder="请选择结束日期" v-model="searchForm.timeRange" type="daterange"  />
        </template>

      </PlusSearch>
    </div>

    <div class="app-container__section">
      <PlusTable
          v-bind="getBinds()"
          :columns="columns"
      >
        <template #empty>
          <el-empty :image-size="80" description="该专业暂无院校开设数据"></el-empty>
        </template>
        <template #title>
           <span class="text-[14px] text-[var(--el-color-info)]">院校列表</span>
        </template>
        <template #toolbar>
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
          >新增</el-button>
          <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="gSelection.length !== 1"
              @click="handleUpdate"
          >修改</el-button>
          <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="gSelection.length === 0"
              @click="handleDelete"
          >删除</el-button>
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
          >导出</el-button>

          <ClockTimer :task="gGetList" />
          <SearchAreaControl v-model="gShowSearchForm" />
        </template>
        <template #plus-cell-status="{row}">
          <dict-tag :options="sys_data_status" :value="row.status"  />
        </template>
        <template #plus-cell-action="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"  >修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" >删除</el-button>
        </template>
      </PlusTable>
    </div>

    <PlusDialogForm
        ref="plusFormInstance"
        v-model:visible="dialogShow"
        v-model="formData"
        :form="{ columns,  labelWidth:'110px',  labelPosition:'right',  rules:formRules }"
        :dialog="{ title: dialogTitle, width: '540px', top: '12vh', confirmLoading }"
        @confirm="handleSubmit"
        @cancel="handleCancel"
    >

    </PlusDialogForm>


  </div>
</template>


<script setup name="ProfessionalSetting">
import {
  listProfessionalSchoolApi,
  delProfessionalSchoolApi,
  updateProfessionalSchoolApi,
  addProfessionalSchoolApi,
  getProfessionalSchoolApi
} from "@/api/edutation/professional";
import {PlusSearch, PlusTable, PlusDialogForm } from 'plus-pro-components'
import { useTablePage } from '@/hooks/useTablePage.js'
import { useActions } from '@/hooks/useActions.js'
import { getCurrentInstance,ref } from "vue"
import {useCommonData} from "@/hooks/useCommonData.js";
import {useRoute} from "vue-router";
const { proxy } = getCurrentInstance();
const { sys_data_status } = proxy.useDict('sys_data_status')

const primaryKey = "id"  // 主键
const route = useRoute();
const proId = computed(()=>route.query.id)

// =============================================
const plusFormInstance = ref(null);
const formInstance = computed(()=>plusFormInstance.value?.formInstance)
const state = reactive({
  dialogShow:false,
  formData:{
    status: "0",
    remark: "",
    schoolId:"",
    proId:"",
    startDate:"",
  },
  formRules:{
    schoolId: [
      { required: true, message: '请选择开设院校', trigger: 'change' },
    ],
    proId: [
      { required: true, message: '请选择开设专业', trigger: 'change' },
    ],
    startDate: [
      { required: true, message: '请选择开设日期', trigger: 'change' },
    ],
  },
  confirmLoading:false,
})
const { formData, confirmLoading, formRules, dialogShow } = toRefs(state)
const isEdit = computed(() =>!!formData.value[primaryKey])
const dialogTitle = computed(() => (isEdit.value ? '编辑' : '新增')+'院校')


const { schoolDataList, getSchoolDataList } = useCommonData() // 获取公共数据
getSchoolDataList()


// =============================================
const columns = computed(()=>[
  {
    label: '开设院校',
    prop: 'schoolId',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'select',
    options: schoolDataList.value,
    optionsMap: { label: 'schoolName', value: 'schoolId' },
    tableColumnProps: {
      align: 'center'
    }
  },

  {
    label: '专业状态',
    prop: 'status',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'select',
    options:sys_data_status.value,
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '开设日期',
    prop: 'startDate',
    hideInSearch:false,
    hideInTable: false,
    hideInForm: false,
    valueType:'date-picker',
    fieldProps:{
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '备注',
    prop: 'remark',
    hideInSearch:true,
    hideInTable: false,
    hideInForm: false,
    valueType:'textarea',
    tableColumnProps: {
      align: 'center'
    },

  },
  {
    label: '操作',
    prop: 'action',
    width: '220px',
    hideInSearch: true,
    hideInForm: true,
    tableColumnProps: {
      align: 'center',
      fixed: 'right'
    }
  }
])

// =============================================
// 列表请求逻辑
const searchForm = ref({})
const {
  gGetList,
  gSelection,
  gShowSearchForm,
  getBinds,
  getSearchBinds
} = useTablePage(listProfessionalSchoolApi, {
  searchForm,
  beforeRequest(query){

    const { timeRange, ...rest } = query;
    const params = proxy.formatRangeTime(timeRange, undefined,'YYYY-MM-DD');

    return { ...rest, params,proId:proId.value }

  }
})

// 删除逻辑
const { deleteAction } = useActions();
function handleDelete(row) {
  deleteAction({
    api: delProfessionalSchoolApi,
    uniqueKey:primaryKey,
    selection:row[primaryKey] || gSelection.value.map(item=>item[primaryKey])
  }).then(() => {
    gGetList();
  });
}

// 新增操作
const handleAdd = ()=>{
  dialogShow.value = true
}

// 取消按钮操作
function handleCancel() {
  dialogShow.value = false
  formData.value = {
    status: "0",
  }
  formInstance.value.resetFields();
}

// 确定按钮操作
const handleSubmit = async () => {
  try {
    confirmLoading.value = true
    if (isEdit.value) {
      await updateProfessionalSchoolApi(formData.value)
      proxy.$modal.msgSuccess("修改成功")
    } else {
      await addProfessionalSchoolApi({ ...formData.value, proId:proId.value })
      proxy.$modal.msgSuccess("新增成功")
    }
    handleCancel();
    await gGetList();
  } catch (error) {
    console.warn('提交错误:', error)
  } finally {
    confirmLoading.value = false
  }
}

// 修改回显数据操作
function handleUpdate(row) {
  const key = row[primaryKey] || gSelection.value[0][primaryKey];
  getProfessionalSchoolApi(key).then(response => {
    formData.value = response.data;
    dialogShow.value = true;
  });
}

// 导出逻辑
const  handleExport = () =>{
  proxy.download(
      'edutation/professional/export',
      {...searchForm.value},
      `professional_${new Date().getTime()}.xlsx`
  )
}
</script>

